﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

using RexToy.Logging;
using RexToy.UI.WinForm.Pmlx;
using RexToy.UI.WinForm.ViewModel;

namespace RexToy.UI.WinForm.Controls
{
    public partial class UserControl : System.Windows.Forms.UserControl, IPmlx, IModelOwner
    {
        private static ILog _log = LogContext.GetLogger<Form>();

        private List<ControlMetaData> _dynamicSizeControls;
        public List<ControlMetaData> DynamicSizeControls
        {
            get { return _dynamicSizeControls; }
        }

        private List<ControlMetaData> _delayComputedControls;
        public List<ControlMetaData> DelayComputedControls
        {
            get { return _delayComputedControls; }
        }

        private ViewModelBase _vm;
        public ViewModelBase ViewModel
        {
            get { return _vm; }
            set
            {
                _vm = value;
                _vm.PropertyChanged += new PropertyChangedEventHandler(_vm_PropertyChanged);
                _doc.ELEngine.Assign(PmlxConstant.CTX_MODEL, _vm);
            }
        }

        void _vm_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            this.UpdateView(this._vm);
        }

        protected PmlxDoc _doc;
        public PmlxDoc PmlxDocument
        {
            get { return _doc; }
        }

        public UserControl()
        {
            _log.Info("Start initialize UserControl [{0}].", this.GetType());

            _dynamicSizeControls = new List<ControlMetaData>();
            _delayComputedControls = new List<ControlMetaData>();
            var locator = PmlxFileLocatorFactory.Create();
            _doc = locator.ReadPmlxFile(this);
            this.Render(_doc);
            this.BindControlFields();

            if (this.ViewModel != null)
            {
                this.ViewModel.Close += () => this.FindForm().Close();
                this.UpdateView(this.ViewModel);
            }

            _log.Info("Initialize UserControl [{0}] success.", this.GetType());
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
                _doc.Dispose();

            base.Dispose(disposing);
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);

            _log.Debug("Start resize dynamic controls inner user control.");
            ControlSizeHelper.Resize(this._dynamicSizeControls);
            _log.Debug("Resize dynamic controls inner user control success.");
        }
    }
}
